package action.upload;

import java.io.File;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import common.interf.IErrorHandle;
import common.interf.IFileHandle;
import common.interf.IServletHandle;

public class UploadAction extends ActionSupport {
	private static final long serialVersionUID = 1L;
	private File file;
	private String fileContentType;
	private String fileFileName;
	private String filePath;
	private IFileHandle fileHandle;
	private IErrorHandle errorHandle;

	private IServletHandle servletHandle;

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	public void setFileHandle(IFileHandle fileHandle) {
		this.fileHandle = fileHandle;
	}

	public void setServletHandle(IServletHandle servletHandle) {
		this.servletHandle = servletHandle;
	}

	public void setErrorHandle(IErrorHandle errorHandle) {
		this.errorHandle = errorHandle;
	}

	// 保存上传图片
	public void save() {
		String s = null;
		try {
			s = fileHandle.saveUploadFile(file, ServletActionContext
					.getServletContext().getRealPath(filePath), fileFileName);
		} catch (Exception e) {
			s = errorHandle.handleErr(e);
		}
		String serverUrl = servletHandle.getServerPath(ServletActionContext
				.getRequest());
		JSONObject jobj = new JSONObject();
		if (null != s) {
			jobj.put("path", serverUrl + filePath + "/" + s);
		} else {
			jobj.put("errors", "保存失败！");
		}
		servletHandle.writeToClient1(ServletActionContext.getResponse(), jobj
				.toString());
	}

	// 删除上传图片
	public void remove() {
		fileHandle.removeUriFile(filePath, ServletActionContext.getRequest()
				.getContextPath(), ServletActionContext.getServletContext()
				.getRealPath("/"));
		servletHandle.writeToClient(ServletActionContext.getResponse(), "1");
	}
}
